<template>
  <div class="gpu-monitor">
    <div class="monitor-header">
      <h4>GPU监控</h4>
      <el-button size="small" :icon="Refresh" @click="loadGpuStatus" :loading="loading">
        刷新
      </el-button>
    </div>

    <div v-if="gpuData.length > 0" class="gpu-list">
      <div 
        v-for="(gpu, index) in gpuData" 
        :key="gpu.id || index"
        class="gpu-card"
      >
        <div class="gpu-header">
          <div class="gpu-info">
            <h5>{{ gpu.name || `GPU ${index}` }}</h5>
            <el-tag 
              :type="gpu.status === 'active' ? 'success' : 'danger'" 
              size="small"
            >
              {{ gpu.status === 'active' ? '活跃' : '离线' }}
            </el-tag>
          </div>
          <div class="gpu-temp">
            <span class="temp-value">{{ gpu.temperature?.current || 0 }}°C</span>
          </div>
        </div>

        <div class="gpu-metrics">
          <!-- GPU使用率 -->
          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-label">GPU使用率</span>
              <span class="metric-value">{{ gpu.usage?.gpu || 0 }}%</span>
            </div>
            <el-progress 
              :percentage="gpu.usage?.gpu || 0" 
              :color="getUsageColor(gpu.usage?.gpu || 0)"
              :show-text="false"
              :stroke-width="6"
            />
          </div>

          <!-- 显存使用率 -->
          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-label">显存使用</span>
              <span class="metric-value">{{ gpu.usage?.memory || 0 }}%</span>
            </div>
            <el-progress 
              :percentage="gpu.usage?.memory || 0" 
              :color="getUsageColor(gpu.usage?.memory || 0)"
              :show-text="false"
              :stroke-width="6"
            />
          </div>

          <!-- 功耗 -->
          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-label">功耗</span>
              <span class="metric-value">{{ gpu.power?.current || 0 }}W</span>
            </div>
            <div class="power-info">
              <span class="power-limit">限制: {{ gpu.power?.limit || 0 }}W</span>
            </div>
          </div>

          <!-- 显存信息 -->
          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-label">显存</span>
              <span class="metric-value">
                {{ formatMemory(gpu.memory?.used || 0) }} / {{ formatMemory(gpu.memory?.total || 0) }}
              </span>
            </div>
          </div>
        </div>

        <!-- 进程信息 -->
        <div v-if="gpu.processes && gpu.processes.length > 0" class="gpu-processes">
          <div class="processes-header">
            <span>运行进程 ({{ gpu.processes.length }})</span>
          </div>
          <div class="processes-list">
            <div 
              v-for="process in gpu.processes.slice(0, 3)" 
              :key="process.pid"
              class="process-item"
            >
              <span class="process-name">{{ process.name || 'Unknown' }}</span>
              <span class="process-memory">{{ formatMemory(process.memory || 0) }}</span>
            </div>
            <div v-if="gpu.processes.length > 3" class="more-processes">
              +{{ gpu.processes.length - 3 }} 更多...
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 无GPU数据时的显示 -->
    <div v-else-if="!loading" class="no-gpu">
      <el-empty description="未检测到GPU设备" />
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- GPU统计图表 -->
    <div class="gpu-charts" style="margin-top: 20px;">
      <div class="chart-header">
        <h5>使用率趋势</h5>
      </div>
      <div class="chart-container">
        <div class="chart-placeholder">
          <el-empty description="图表功能开发中..." />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { gpuApi } from '@/api/gpu'

// 响应式数据
const gpuData = ref([])
const loading = ref(false)
let refreshTimer = null

// 加载GPU状态
const loadGpuStatus = async () => {
  loading.value = true
  try {
    const response = await gpuApi.getStatus()
    if (response.code === 200) {
      // 确保数据是数组格式
      const data = response.data
      if (Array.isArray(data)) {
        gpuData.value = data
      } else if (data && typeof data === 'object') {
        gpuData.value = [data]
      } else {
        gpuData.value = []
      }
    } else {
      throw new Error(response.msg || 'GPU状态获取失败')
    }
  } catch (error) {
    console.error('获取GPU状态失败:', error)
    // 使用模拟数据作为后备
    gpuData.value = generateMockGpuData()
  } finally {
    loading.value = false
  }
}

// 生成模拟GPU数据
const generateMockGpuData = () => {
  return [
    {
      id: 'gpu_0',
      name: 'NVIDIA GeForce RTX 4090',
      status: 'active',
      usage: {
        gpu: Math.floor(Math.random() * 40) + 60,
        memory: Math.floor(Math.random() * 30) + 50,
        encoder: Math.floor(Math.random() * 20) + 10,
        decoder: Math.floor(Math.random() * 15) + 5
      },
      memory: {
        total: 24576, // 24GB
        used: Math.floor(Math.random() * 12288) + 6144,
        free: 0
      },
      temperature: {
        current: Math.floor(Math.random() * 20) + 65,
        max: 83
      },
      power: {
        current: Math.floor(Math.random() * 100) + 250,
        limit: 450,
        max: 450
      },
      fan: {
        speed: Math.floor(Math.random() * 30) + 40
      },
      processes: [
        { pid: 1234, name: 'python.exe', memory: 2048 },
        { pid: 5678, name: 'ai_service.exe', memory: 4096 },
        { pid: 9012, name: 'video_processor.exe', memory: 1024 }
      ],
      driver_version: '535.98',
      cuda_version: '12.2'
    }
  ]
}

// 获取使用率颜色
const getUsageColor = (percentage) => {
  if (percentage >= 90) return '#f56c6c'
  if (percentage >= 70) return '#e6a23c'
  if (percentage >= 50) return '#409eff'
  return '#67c23a'
}

// 格式化内存大小
const formatMemory = (mb) => {
  if (mb >= 1024) {
    return (mb / 1024).toFixed(1) + ' GB'
  }
  return mb + ' MB'
}

// 生命周期
onMounted(() => {
  loadGpuStatus()
  
  // 每10秒刷新一次GPU状态
  refreshTimer = setInterval(() => {
    if (!loading.value) {
      loadGpuStatus()
    }
  }, 10000)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style lang="scss" scoped>
.gpu-monitor {
  .monitor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h4 {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .gpu-list {
    .gpu-card {
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;
      
      .gpu-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        .gpu-info {
          h5 {
            margin: 0 0 4px 0;
            font-size: 14px;
            font-weight: 600;
            color: #303133;
          }
        }
        
        .gpu-temp {
          .temp-value {
            font-size: 16px;
            font-weight: 600;
            color: #e6a23c;
          }
        }
      }
      
      .gpu-metrics {
        .metric-item {
          margin-bottom: 12px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .metric-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;
            
            .metric-label {
              font-size: 12px;
              color: #909399;
            }
            
            .metric-value {
              font-size: 12px;
              font-weight: 600;
              color: #303133;
            }
          }
          
          .power-info {
            margin-top: 4px;
            
            .power-limit {
              font-size: 11px;
              color: #909399;
            }
          }
        }
      }
      
      .gpu-processes {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #f5f7fa;
        
        .processes-header {
          font-size: 12px;
          color: #909399;
          margin-bottom: 8px;
        }
        
        .processes-list {
          .process-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 4px 0;
            font-size: 11px;
            
            .process-name {
              color: #303133;
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .process-memory {
              color: #909399;
              margin-left: 8px;
            }
          }
          
          .more-processes {
            font-size: 11px;
            color: #909399;
            text-align: center;
            padding: 4px 0;
          }
        }
      }
    }
  }
  
  .no-gpu {
    text-align: center;
    padding: 40px 0;
  }
  
  .loading-state {
    padding: 16px;
  }
  
  .gpu-charts {
    .chart-header {
      margin-bottom: 12px;
      
      h5 {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .chart-container {
      .chart-placeholder {
        height: 150px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fafafa;
        border-radius: 4px;
        border: 1px solid #e4e7ed;
      }
    }
  }
}

.dark .gpu-monitor {
  .monitor-header h4 {
    color: #e4e7ed;
  }
  
  .gpu-list .gpu-card {
    background: #2d2d2d;
    border-color: #4c4d4f;
    
    .gpu-header .gpu-info h5 {
      color: #e4e7ed;
    }
    
    .gpu-metrics .metric-item .metric-header .metric-value {
      color: #e4e7ed;
    }
    
    .gpu-processes {
      border-top-color: #4c4d4f;
      
      .processes-list .process-item .process-name {
        color: #e4e7ed;
      }
    }
  }
  
  .gpu-charts {
    .chart-header h5 {
      color: #e4e7ed;
    }
    
    .chart-container .chart-placeholder {
      background: #2d2d2d;
      border-color: #4c4d4f;
    }
  }
}
</style>